import * as vscode from 'vscode';
import { ComponentDataStore } from '@/config/component-data';

/**
 * 组件属性补全提供程序
 * 负责在JSX/TSX文件中提供智能补全建议
 */
export class ComponentCompletionProvider implements vscode.CompletionItemProvider {
    private dataStore = ComponentDataStore.getInstance();

    /**
     * 提供补全项的主方法
     * @param document 当前文档
     * @param position 光标位置
     * @param token 取消令牌
     * @param context 补全上下文
     */
    provideCompletionItems(
        document: vscode.TextDocument,
        position: vscode.Position,
        token: vscode.CancellationToken,
        context: vscode.CompletionContext
    ): vscode.ProviderResult<vscode.CompletionItem[]> {
        const completions: vscode.CompletionItem[] = [];
        const lineText = document.lineAt(position).text;
        const linePrefix = lineText.substring(0, position.character);
        try {
            // 1. 组件标签补全
            if (this.shouldSuggestComponent(linePrefix)) {
                this.addComponentSuggestions(completions, linePrefix, position, document);
            }

            // 2. 组件属性补全（支持别名）
            if (this.shouldSuggestProps(linePrefix)) {
                const componentName = this.extractComponentName(linePrefix, true); // 启用模糊匹配
                this.addPropSuggestions(completions, componentName, linePrefix);
            }

            // 3. 属性值补全
            if (this.shouldSuggestPropValues(linePrefix)) {
                const { componentName, propName } = this.extractPropInfo(linePrefix);
                this.addPropValueSuggestions(completions, componentName, propName);
            }
        } catch (error) {
            console.error('补全提供程序错误:', error);
        }
        return completions;
    }

    // 添加组件建议
    private addComponentSuggestions(
        completions: vscode.CompletionItem[],
        linePrefix: string,
        position: vscode.Position,
        document: vscode.TextDocument
    ): void {
        const components = this.dataStore.getAllComponents();
        const partialName = this.extractPartialComponentName(linePrefix);
        
        // 如果没有部分输入，显示所有组件
        if (!partialName) {
            this.addAllComponents(completions, components);
            return;
        }

        // 根据部分输入过滤和排序组件
        const matchedComponents = this.getMatchingComponents(components, partialName);
        
    

       for (const component of matchedComponents) {
            const item = this.createComponentCompletionItem(component, partialName);
            completions.push(item);
            
            // 为别名也创建补全项
            if (component.aliases) {
                for (const alias of component.aliases) {
                    if (this.matchesPartialInput(alias, partialName)) {
                        const aliasItem = this.createAliasCompletionItem(alias, component, partialName);
                        completions.push(aliasItem);
                    }
                }
            }
        }
         // 如果没有找到匹配的组件，显示所有组件
        if (completions.length === 0) {
            this.addAllComponents(completions, components);
        }
    }

     // 添加属性建议
    private addPropSuggestions(
        completions: vscode.CompletionItem[], 
        componentName: string, 
        linePrefix: string
    ): void {
         const component = this.dataStore.getComponent(componentName);
        if (!component) {return;}

        const existingProps = this.extractExistingProps(linePrefix);

         for (const prop of component.props) {
            if (existingProps.includes(prop.name)) {continue;}

            const item = new vscode.CompletionItem(prop.name, vscode.CompletionItemKind.Property);
            item.detail = `${prop.type}${prop.required ? ' (必填)' : ''}`;
            item.documentation = prop.description;
            
            this.setInsertTextForProp(item, prop);
            
            if (prop.required) {
                item.sortText = `0${prop.name}`;
                item.detail = `🔴 ${item.detail}`;
            } else {
                item.sortText = `1${prop.name}`;
            }

            completions.push(item);
        }
    }

     // 添加属性值建议
    private addPropValueSuggestions(
        completions: vscode.CompletionItem[], 
        componentName: string, 
        propName: string
    ): void {
        const component = this.dataStore.getComponent(componentName);
        if (!component) {return;}

        const prop = component.props.find(p => p.name === propName);
        if (!prop || !prop.options) {return;}
        
        for (const option of prop.options) {
            const cleanOption = option.replace(/'/g, '');
            const item = new vscode.CompletionItem(cleanOption, vscode.CompletionItemKind.Value);
            item.detail = `可选值: ${cleanOption}`;
            item.insertText = `"${cleanOption}"`;
            completions.push(item);
        }
    }

    // 添加所有组件（无过滤）
    private addAllComponents(completions: vscode.CompletionItem[], components: any[]): void {
        for (const component of components) {
            const item = this.createComponentCompletionItem(component, '');
            completions.push(item);
            
            if (component.aliases) {
                for (const alias of component.aliases) {
                    const aliasItem = this.createAliasCompletionItem(alias, component, '');
                    completions.push(aliasItem);
                }
            }
        }
    }

    // 获取匹配的组件列表（智能排序）
    private getMatchingComponents(components: any[], partialInput: string): any[] {
        const matches: { component: any; score: number }[] = [];
        const lowerPartial = partialInput.toLowerCase();

        for (const component of components) {
            let score = 0;

            // 检查组件名称匹配
            const nameMatch = this.calculateMatchScore(component.name, lowerPartial);
            if (nameMatch.score > 0) {
                score = nameMatch.score;
                // 开头匹配得分更高
                if (nameMatch.isPrefix) {
                    score += 100;
                }
            }

            // 检查别名匹配
            if (component.aliases) {
                for (const alias of component.aliases) {
                    const aliasMatch = this.calculateMatchScore(alias, lowerPartial);
                    if (aliasMatch.score > score) {
                        score = aliasMatch.score;
                        // 别名匹配得分略低
                        score -= 10;
                    }
                }
            }

            if (score > 0) {
                matches.push({ component, score });
            }
        }

        // 按匹配分数排序
        return matches.sort((a, b) => b.score - a.score).map(match => match.component);
    }

    // 计算匹配分数
    private calculateMatchScore(text: string, partialInput: string): { score: number; isPrefix: boolean } {
        const lowerText = text.toLowerCase();
        
        // 精确匹配
        if (lowerText === partialInput) {
            return { score: 1000, isPrefix: true };
        }

        // 开头匹配（例如：but → button）
        if (lowerText.startsWith(partialInput)) {
            return { score: 500 + partialInput.length, isPrefix: true };
        }

        // 包含匹配（例如：but → beautiful-button）
        if (lowerText.includes(partialInput)) {
            const position = lowerText.indexOf(partialInput);
            // 位置越靠前得分越高
            return { score: 300 + (text.length - position), isPrefix: false };
        }

        // 模糊匹配（例如：bt → button）
        let fuzzyScore = 0;
        let searchIndex = 0;
        
        for (let i = 0; i < lowerText.length && searchIndex < partialInput.length; i++) {
            if (lowerText[i] === partialInput[searchIndex]) {
                fuzzyScore += 10;
                searchIndex++;
            }
        }

        if (searchIndex === partialInput.length) {
            return { score: 100 + fuzzyScore, isPrefix: false };
        }

        return { score: 0, isPrefix: false };
    }

    // 创建组件补全项,支持高亮匹配部分
   private createComponentCompletionItem(component: any, partialInput: string): vscode.CompletionItem {
        const item = new vscode.CompletionItem(component.name, vscode.CompletionItemKind.Class);
        item.detail = `组件: ${component.name}`;
        item.documentation = component.description;
        
        // 设置插入文本
        item.insertText = new vscode.SnippetString(`${component.name}$0`);
        
        // 设置标签显示（高亮匹配部分）
        if (partialInput && component.name.toLowerCase().includes(partialInput.toLowerCase())) {
            const matchIndex = component.name.toLowerCase().indexOf(partialInput.toLowerCase());
            const beforeMatch = component.name.substring(0, matchIndex);
            const matchText = component.name.substring(matchIndex, matchIndex + partialInput.length);
            const afterMatch = component.name.substring(matchIndex + partialInput.length);
            
            item.label = {
                label: component.name,
                description: component.description,
                detail: `匹配: ${beforeMatch}${matchText}${afterMatch}`
            };
        } else {
            item.label = component.name;
        }

        // 设置排序文本（确保匹配度高的排在前面）
        if (partialInput) {
            const isExactMatch = component.name.toLowerCase() === partialInput.toLowerCase();
            const isPrefixMatch = component.name.toLowerCase().startsWith(partialInput.toLowerCase());
            
            if (isExactMatch) {
                item.sortText = `0${component.name}`;
            } else if (isPrefixMatch) {
                item.sortText = `1${component.name}`;
            } else {
                item.sortText = `2${component.name}`;
            }
        } else {
            item.sortText = `3${component.name}`;
        }

        // 添加自动导入命令
        if (component.importPath) {
            item.command = {
                command: 'componentCompletion.addImport',
                title: '自动添加导入',
                arguments: [component.name, component.importPath]
            };
        }

        return item;
    }

    // 创建别名补全项
    private createAliasCompletionItem(alias: string, component: any, partialInput: string): vscode.CompletionItem {
        const item = new vscode.CompletionItem(alias, vscode.CompletionItemKind.Class);
        item.detail = `别名 → ${component.name}`;
        item.documentation = `输入 "${alias}" 将使用 ${component.name} 组件`;
        item.insertText = new vscode.SnippetString(`${component.name}$0`);
        
        // 设置排序文本（别名排在正式名称后面）
        if (partialInput) {
            const isExactMatch = alias.toLowerCase() === partialInput.toLowerCase();
            const isPrefixMatch = alias.toLowerCase().startsWith(partialInput.toLowerCase());
            
            if (isExactMatch) {
                item.sortText = `0${alias}`;
            } else if (isPrefixMatch) {
                item.sortText = `1${alias}`;
            } else {
                item.sortText = `2${alias}`;
            }
        } else {
            item.sortText = `4${alias}`;
        }

        return item;
    }


    // 根据属性类型设置插入文本
     private setInsertTextForProp(item: vscode.CompletionItem, prop: any): void {
        if (prop.type === 'boolean') {
            item.insertText = new vscode.SnippetString(`${prop.name}={${prop.defaultValue || false}}$0`);
        } else if (prop.options && prop.options.length > 0) {
            const options = prop.options.map((opt: string) => opt.replace(/'/g, ''));
            item.insertText = new vscode.SnippetString(`${prop.name}="\${1|${options.join(',')}|}"$0`);
        } else if (prop.type.includes('=>')) {
            item.insertText = new vscode.SnippetString(`${prop.name}={\${1:() => {\\}\}}$0`);
        } else if (prop.type.includes('string')) {
            item.insertText = new vscode.SnippetString(`${prop.name}="\${1:${prop.defaultValue || ''}}"$0`);
        } else {
            item.insertText = new vscode.SnippetString(`${prop.name}={\${1:${prop.defaultValue || ''}}\}$0`);
        }
    }

     // 检查是否应该建议组件,支持输入过程中的部分匹配
    private shouldSuggestComponent(linePrefix: string): boolean {
        // 1. 以 < 开头（新标签）
        if (linePrefix.endsWith('<')) {
            return true;
        }
        
        // 2. 输入过程中的部分组件名（例如：<but）
        if (linePrefix.includes('<') && /<[a-zA-Z][a-zA-Z0-9]*$/.test(linePrefix)) {
            return true;
        }
        
        // 3. 标签结束前的空格（显示属性补全）
        if (linePrefix.includes('<') && linePrefix.includes(' ') && !linePrefix.endsWith('>')) {
            return false; // 这里返回false，由shouldSuggestProps处理
        }
        
        return false;
    }

    // 检查是否应该建议属性
    private shouldSuggestProps(linePrefix: string): boolean {
       const hasComponent = linePrefix.includes('<') && /<[a-zA-Z]/.test(linePrefix);
        const hasSpaceAfterComponent = hasComponent && linePrefix.includes(' ');
        const notEnded = !linePrefix.endsWith('>');
        return hasComponent && hasSpaceAfterComponent && notEnded;
    }

    // 检查是否应该建议属性值
    private shouldSuggestPropValues(linePrefix: string): boolean {
        return linePrefix.includes('=') && linePrefix.includes('"') && !linePrefix.endsWith('"');
    }

    // 提取组件名（支持模糊匹配）
    private extractComponentName(linePrefix: string, fuzzyMatch: boolean = false): string {
        const match = linePrefix.match(/<([a-zA-Z][a-zA-Z0-9]*)/);
        return match ? match[1] : '';
    }

    // 提取部分组件名,支持输入过程中的部分匹配
   private extractPartialComponentName(linePrefix: string): string {
        // 匹配 <but 这种情况（输入过程中的部分组件名）
        const partialMatch = linePrefix.match(/<([a-zA-Z][a-zA-Z0-9]*)$/);
        if (partialMatch) {
            return partialMatch[1];
        }
        
        // 匹配 <Button 这种情况（完整组件名后的空格）
        const fullMatch = linePrefix.match(/<([a-zA-Z][a-zA-Z0-9]*)\s+$/);
        if (fullMatch) {
            return ''; // 返回空字符串表示需要显示属性补全
        }
        
        return '';
    }

    // 从文本中提取属性信息
    private extractPropInfo(linePrefix: string): { componentName: string; propName: string } {
        const componentMatch = linePrefix.match(/<([a-zA-Z][a-zA-Z0-9]*)/);
        const propMatch = linePrefix.match(/([a-zA-Z][a-zA-Z0-9]*)="?$/);
        return {
            componentName: componentMatch ? componentMatch[1] : '',
            propName: propMatch ? propMatch[1] : ''
        };
    }

     // 提取已存在的属性
    private extractExistingProps(linePrefix: string): string[] {
        const propMatches = linePrefix.match(/([a-zA-Z][a-zA-Z0-9]*)=/g) || [];
        return propMatches.map(prop => prop.replace('=', ''));
    }

     // 检查组件是否匹配部分输入
   private matchesPartialInput(text: string, partialInput: string): boolean {
        if (!partialInput) {return true;}
        
        const lowerText = text.toLowerCase();
        const lowerPartial = partialInput.toLowerCase();
        
        return lowerText.includes(lowerPartial) || this.fuzzyMatch(lowerText, lowerPartial);
    }

    // 模糊匹配
    private fuzzyMatch(text: string, search: string): boolean {
        if (search.length === 0) {return true;}
        if (search.length > text.length) {return false;}
        
        let searchIndex = 0;
        for (let i = 0; i < text.length && searchIndex < search.length; i++) {
            if (text[i] === search[searchIndex]) {
                searchIndex++;
            }
        }
        
        return searchIndex === search.length;
    }

    // 解析补全项（可选实现）
    resolveCompletionItem?(item: vscode.CompletionItem, token: vscode.CancellationToken): vscode.ProviderResult<vscode.CompletionItem> {
        // 可以在这里延迟加载更详细的信息
        return item;
    }
}